package com.lindroy.androidplayer.ui.login

import androidx.fragment.app.viewModels
import android.content.Context
import android.os.Bundle
import com.google.gson.Gson
import com.lindroid.androidutilskt.statics.AppManager
import com.lindroy.androidplayer.MainActivity
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseFragment
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.constants.SP_KEY_LOGIN_INFO
import com.lindroy.androidplayer.extensions.*
import com.lindroy.lib_utils.extensions.isTextEmpty
import com.lindroy.lib_utils.extensions.putSpString
import com.lindroy.lib_utils.extensions.shortToast
import com.lindroy.lib_utils.extensions.textString
import kotlinx.android.synthetic.main.fragment_register.*


class RegisterFragment(override val layoutId: Int = R.layout.fragment_register) : BaseLazyFragment() {

    private val registerViewModel: LoginViewModel by viewModels()

    private var listener: OnLoginClickListener? = null


    override fun initView() {

    }

    override fun lazyLoad() {
        registerViewModel.loginResult.observe(this) { resultState ->
            parseState(resultState, onError = {
                shortToast(it.errorMsg)
            }) { loginResp ->
                putSpString(SP_KEY_LOGIN_INFO, Gson().toJson(loginResp))
                AppManager.finishAllActivity()
                context?.let { MainActivity.start(it) }
            }
        }
    }

    override fun initListener() {
        tvLogin.setOnClickListener {
            listener?.onLoginClick()
        }
        etPwd.setInputLetterSpacing()
        etRePwd.setInputLetterSpacing()

        btnRegister.setOnClickListener {
            register()
        }
    }

    override fun initClick() {

    }


    private fun register() {
        if (etName.isTextEmpty) {
            shortToast("用户名不能为空")
            return
        }
        if (etPwd.isTextEmpty) {
            shortToast("密码不能为空")
            return
        }
        if (etRePwd.textString != etPwd.textString) {
            shortToast("两次输入的密码不一致")
            return
        }
//        showLoading()

        registerViewModel.registerAndLogin(etName.textString, etPwd.textString)

        /*registerViewModel.register(etName.textString, etPwd.textString, etRePwd.textString)
            .observe(this, {
                val result = it.getOrNull()
                if (result.isNotNull()) {
                    LoginEvent(true).post()
                }
            })*/
    }


    companion object {
        @JvmStatic
        fun newInstance() =
            RegisterFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as? OnLoginClickListener
    }

    interface OnLoginClickListener {
        fun onLoginClick()
    }
}